package com.version1.diabeco.service;

import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.os.Parcel;
import android.os.RemoteException;
import android.widget.Toast;

import com.version1.diabeco.ActivityMain;
import com.version1.diabeco.R;
import com.version1.diabeco.model.mapas.Geocerca;

public class AlarmaService extends Service {

	private PendingIntent alarmSender;

	private static int NOTIFICATIONS = R.layout.activity_ayuda;
	public static final String BROADCAST_TEXT = "AlarmaServiceBroadcastText";

	private NotificationManager notificationManager;

	@Override
	public void onCreate() {
		notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

		alarmSender = PendingIntent.getService(this, 0, new Intent(this, ActivityMain.class), 0);

//		Toast.makeText(this, "Servicio de Alarma Activado", Toast.LENGTH_SHORT).show();

//		AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
//		AlarmaInicializador.inicializarAlarmas(this.getBaseContext(), am);

		// Start up the thread running the service. Note that we create a
		// separate thread because the service normally runs in the process's
		// main thread, which we don't want to block.
		Thread thr = new Thread(null, alarmTask, "Alarm Service");
		thr.start();
	}

	@Override
	public void onDestroy() {
		notificationManager.cancel(NOTIFICATIONS);

		Toast.makeText(this, "Servicio de Alarma Desactivado", Toast.LENGTH_SHORT).show();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// initGPS(); // sets up the LocationManager mgr
		// if (preferredProvider != null) {
		// mgr.requestLocationUpdates(preferredProvider, MIN_SECONDS * 1000, MIN_METRES, this);
		// return START_STICKY;
		// }
		return START_STICKY;
	}

	@Override
	public IBinder onBind(Intent intent) {
		return mBinder;
	}

	@Override
	public boolean onUnbind(Intent intent) {
		// mgr.removeUpdates(this);
		return super.onUnbind(intent);
	}

	/**
	 * The function that runs in our worker thread
	 */
	Runnable alarmTask = new Runnable() {

		public void run() {

			// proceso infinito
			while (true) {
				synchronized (mBinder) {
					try {

						// Un ciclo cada 10 segundos
						mBinder.wait(60000);

//						System.out.println("Ciclo servicio de alarma ejecutado.");

					} catch (Exception e) {
					}
				}
			}

			// // Done with our work... stop the service!
			// LocationService.this.stopSelf();
		}
	};

	private void showAlarmaNotification(Geocerca geocerca, boolean showSpecificActivity, int imageId, String text) {

		// The PendingIntent to launch our activity if the user selects this notification
		PendingIntent contentIntent = null;
		if (showSpecificActivity) {
			// Intent intent = ActivityMapasHelper.getGeocercaIntent(geocerca, this);
			// contentIntent = PendingIntent.getActivity(this, 0, intent, 0);
		} else {
			Intent intent = new Intent(AlarmaService.this, ActivityMain.class);
			contentIntent = PendingIntent.getActivity(this, 0, intent, 0);
		}
		this.showNotification(imageId, text, contentIntent);
	}

	private void showNotification(int imageId, String text, PendingIntent contentIntent) {

		// Set the icon, scrolling text and timestamp.
		// Note that in this example, we pass null for tickerText. We update the icon enough that
		// it is distracting to show the ticker text every time it changes. We strongly suggest
		// that you do this as well. (Think of of the "New hardware found" or "Network connection
		// changed" messages that always pop up)
		Notification notification = new Notification(imageId, null, System.currentTimeMillis());

		// Set the info for the views that show in the notification panel.
		notification.setLatestEventInfo(this, getText(R.string.ajustes_titulo_alarma), text, contentIntent);

		// notification.flags = Notification.FLAG_INSISTENT | Notification.FLAG_AUTO_CANCEL;
		notification.flags |= Notification.FLAG_AUTO_CANCEL;

		notification.defaults |= Notification.DEFAULT_SOUND;
		notification.defaults |= Notification.DEFAULT_VIBRATE;

		// Send the notification.
		// We use a layout id because it is a unique number. We use it later to cancel.
		notificationManager.notify(NOTIFICATIONS, notification);

	}

	void showMessage(String msg) {
//		Toast.makeText(this, "Alarm Service " + msg, Toast.LENGTH_SHORT).show();
	}

	/**
	 * This is the object that receives interactions from clients. See RemoteService for a more complete example.
	 */
	private final IBinder mBinder = new Binder() {
		@Override
		protected boolean onTransact(int code, Parcel data, Parcel reply, int flags) throws RemoteException {
			return super.onTransact(code, data, reply, flags);
		}
	};

}
